import React, { useImperativeHandle, useState } from 'react';
import PropTypes from 'prop-types';
import { Button, Form, Spin, message, Icon, Divider } from 'antd';
import cn from 'classnames';
import styles from './index.less';

/**
 * 表单容器
 */
const FormContainer = React.forwardRef(
    (
        { form, title, onSubmit, onCancel, onEdit, hasEditAuth, defaultEdit, customControls, isEntryGuide, ...props },
        ref
    ) => {
        // 编辑状态
        const [editStatus, setEditStatus] = useState(!!defaultEdit);
        const [loading, setLoading] = useState(false);

        // 保存
        const handleSubmit = e => {
            e.preventDefault();
            form.validateFields(async (errors, values) => {
                if (!errors && onSubmit) {
                    try {
                        setLoading(true);
                        await onSubmit(values, form);
                        setLoading(false);
                        setEditStatus(false);
                    } catch (error) {
                        setLoading(false);
                        message.error(error.message);
                    }
                }
            });
        };

        // 取消编辑
        const handleCancel = () => {
            if (onCancel) {
                const cancelResult = onCancel();
                if (cancelResult !== false) {
                    setEditStatus(false);
                    form.resetFields();
                }
            } else {
                setEditStatus(false);
                form.resetFields();
            }
        };

        // 编辑
        const handleEdit = () => {
            if (onEdit) {
                onEdit();
            }
            setEditStatus(true);
        };

        useImperativeHandle(ref, () => ({
            form
        }));

        // 渲染编辑按钮, 要判断是否有权限
        const renderEditButton = () => {
            if (hasEditAuth) {
                return isEntryGuide ? (
                    <Button onClick={handleEdit}>
                        编辑
                    </Button>
                ) : (
                    <Button className="edit" type="link" size="small" onClick={handleEdit}>
                        <Icon type="edit" />
                        编辑
                    </Button>
                )
            }
            return null
        };

        // 渲染控制栏
        const renderControls = () => {
            if (customControls) {
                return customControls({ editStatus, loading, handleSubmit, handleCancel });
            }
            if (onSubmit) {
                if (editStatus) {
                    return (
                        <div>
                            {isEntryGuide ? (
                                <>
                                    <Button onClick={handleCancel}>
                                        取消
                                    </Button>
                                    &emsp;
                                    <Button type="primary" onClick={handleSubmit} loading={loading}>
                                        保存
                                    </Button>
                                </>
                            ) : (
                                <>
                                    <Button type="link" size="small" onClick={handleCancel}>
                                        <Icon type="close" />
                                        取消
                                    </Button>
                                    <Divider type="vertical" />
                                    <Button type="link" size="small" onClick={handleSubmit} loading={loading}>
                                        <Icon type="check" />
                                        保存
                                    </Button>
                                </>
                            )}
                            &emsp;
                        </div>
                    );
                }
                return renderEditButton();
            }
            return null;
        };

        // render
        return (
            <Spin spinning={loading}>
                <div className={cn(styles.formContainer, isEntryGuide && styles.formLayoutEntryGuide)}>
                    <div className="sectionHeader">{title}</div>
                    <div className="sectionControls">{renderControls()}</div>
                    <Form className={editStatus ? 'formEdit' : 'formView'} {...props}>
                        {props.children(form, editStatus)}
                    </Form>
                </div>
            </Spin>
        );
    }
);

// prop
FormContainer.propTypes = {
    title: PropTypes.any.isRequired,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
    hasEditAuth: PropTypes.bool,
    defaultEdit: PropTypes.bool,
    // formItemLayout: PropTypes.object,
    customControls: PropTypes.func
};

FormContainer.defaultProps = {
    onSubmit: null,
    onCancel: null,
    hasEditAuth: true,
    defaultEdit: false,
    // formItemLayout: {
    //     labelCol: {
    //         md: { span: 8 },
    //         xs: { span: 24 },
    //         sm: { span: 24 }
    //     },
    //     wrapperCol: {
    //         md: { span: 15 },
    //         xs: { span: 24 },
    //         sm: { span: 24 }
    //     }
    // },
    customControls: null
};

export const fullRowFormItemLayout = {
    labelCol: {
        md: { span: 4 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 19 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};

export default Form.create()(FormContainer);
